<?php


namespace Create\Api;


/**
 * 创建数据表格
 * @author Administrator
 */
class Databases
{
    private $conn = null; //数据连接
    private $name = ''; //控制器名称
    private $comment = ''; //控制器中文注释
    private $engine = '';//表引擎
    private $data = array();
    private $conf = array(
        'host' => 'localhost',
        'user' => 'root',
        'pwd' => 'root',
        'charset' => 'utf8',
        'dbname' => 'demo',
        'perfix' => 'demo_'
    );//数据库连接

    public function __construct($name = "表名称", $comment = '表注释', $engine = '表引擎', $data = '数据')
    {
        $charset = strtolower(C('DEFAULT_CHARSET')) ;
        $this->conf = array(
            'host' => C('DB_HOST'),
            'user' => C('DB_USER'),
            'pwd' => C('DB_PWD'),
            'charset' => $charset==='utf-8' ? 'utf8' : $charset ,
            'dbname' => C('DB_NAME'),
            'perfix' => C('DB_PREFIX')
        );
        $this->name = $name;
        $this->comment = $comment;
        $this->engine = $engine;
        $this->data = $data;
        $this->conn = mysql_connect($this->conf['host'], $this->conf['user'], $this->conf['pwd']);
        if (!$this->conn) {
            exit(mysql_error());
        }
        mysql_query('set names ' . $this->conf['charset'], $this->conn);
        mysql_query('use ' . $this->conf['dbname'], $this->conn);

    }

    //创建数据表
    public function create()
    {
        $sql = $this->create_table_sql();
        $sql_arr = explode(';', $sql);
        foreach ($sql_arr as $v) {
            $status = mysql_query($v, $this->conn);
            if ($status === false) {
                return false;
            }
        }
        return true;
    }

    /**
     * 产生一条sql
     * return string sql
     */
    private function create_table_sql()
    {
        $data      = $this->data;
        $tablename = $this->conf['perfix'] . $this->name;
        $sql       = "DROP TABLE IF EXISTS `{$tablename}`; ";
        $sql       .= "CREATE TABLE `{$tablename}` (";
        $insex_str = '';//索引字符串
        foreach ($data as $k => $v) {
            $length = empty($v['lengths']) ? 11 : $v['lengths'];

            //字段的区别处理
            if(($v['types'] == 'longtext') || ($v['types'] == 'text'))
            {
                $sql .= "`{$v['fields']}` {$v['types']} ";
            }
            else
            {
                $sql .= "`{$v['fields']}` {$v['types']}({$length}) ";
            }

            if ($v['ai']) {
                $sql .= " AUTO_INCREMENT ";
            }
            $sql .= 'NOT NULL ';
            if ($v['defaults']) {
                $sql .= " DEFAULT '{$v['defaults']}'";
            }
            if ($v['comment']) {
                $sql .= " COMMENT '{$v['comment']}' ";
            }
            $sql .= ',';
            //主键与索引生成
            if ($v['indexs'] == 'primary key') {
                $insex_str .= " PRIMARY KEY (`{$v['fields']}`),";
            }
            else if ($v['indexs'] == 'index')
            {
                $insex_str .= " KEY `{$tablename}_{$v['fields']}` (`{$v['fields']}`),";
            }
        }
        $sql .= $insex_str;
        $sql = substr($sql, 0, -1);
        $sql .= ')ENGINE ' . $this->engine . ' CHARSET=' . $this->conf['charset'] . ' COMMENT="' . $this->comment . '"';
        return $sql;
    }

    public function __destruct()
    {
        mysql_close($this->conn);
    }


}
